package ua.kpi.apolonov.IO;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * Class for service of files
 * @version 1.2 25.02.2013
 * @author Yegor Apolonov
 */

public class ExternalFileService {
	
	private File dataFile;
	private FileReader fileReader;
	private FileWriter fileWriter;
	private BufferedReader bufferedReader;
	
	public ExternalFileService(String externalFile) {
		dataFile = new File(externalFile);
	}
	
	public String[] readExternalFile() throws IOException {
		int ArrayRange = calculateLinesInDataFile();
		String[] bufferString = new String[ArrayRange];
		initializeFileReader();
		for(int lineNumber = 0; lineNumber < ArrayRange; lineNumber++) {
			bufferString[lineNumber] = bufferedReader.readLine();
		}
		closeFileReader();
		return bufferString;
	}
	
	public void writeToExternalFile(String dataLine) {
		try {
			initializeFileWriter();
			fileWriter.write(dataLine);
			closeFileWriter();
		} catch(IOException e) {
			System.err.println("Ой, какая незадача... Файл учетной записи не сохранен:(");
		}
	}
	
	public boolean isFileExists() {
		String fileName = String.format("%s%s%s", "src/ua/kpi/apolonov/users/", dataFile, ".txt");
		return new File(fileName).exists();
	}
	
	private void initializeFileReader() throws FileNotFoundException {
		fileReader = new FileReader(dataFile);
		bufferedReader = new BufferedReader(fileReader);
	}
	
	private void initializeFileWriter() throws IOException {
		fileWriter = new FileWriter(dataFile, true);
	}
	
	private void closeFileReader() throws IOException {
		bufferedReader.close();
		fileReader.close();
	}
	
	private void closeFileWriter() throws IOException {
		fileWriter.close();
	}
	
	private int calculateLinesInDataFile() throws IOException {
		int numberOfLines = 0;
		initializeFileReader();
		while(bufferedReader.readLine() != null) {
			numberOfLines++;
		}
		closeFileReader();
		return numberOfLines;
	}
	
}